
#ifndef _FONTS_H_
#define _FONTS_H_

#define FONT_SIZE (32)

enum _font_sizes {
    FS_LARGE = 0,
    FS_MED,
    FS_SMALL
};


class fonts {
    public:

    TTF_Font* fontset;
    int color_r;
    int color_g;
    int color_b;
    int px_size;


    fonts() :  fontset(0), px_size(12)
    {

        if (TTF_Init() == -1) return;

        fontset = loadfont("FreeSansBold.ttf",px_size);
        if (!fontset) exit(0);

    };

    void set_font_size(int px)
    {
        if (px_size != px)
        {
            TTF_CloseFont(fontset);
        }

        px_size = px;
        fontset = loadfont("FreeSansBold.ttf",px_size);

    }

    TTF_Font* loadfont(char* file, int ptsize)
    {
        TTF_Font* tmpfont;
        tmpfont = TTF_OpenFont(file, ptsize);
        if (tmpfont == NULL)
            return 0;

        change_color(80,80,80);

        return tmpfont;
    };

    ~fonts()
    {
        TTF_CloseFont(fontset);
        TTF_Quit();

    };

    void change_color(int r, int g, int b)
    {
        color_r = r;
        color_g = g;
        color_b = b;
    };


    int get_length_px(char* t)
    {

        int w,h;

        TTF_SizeText(fontset, t, &w, &h);

        return w;
    };

    void set_style(int style)
    {
        TTF_SetFontStyle(fontset, style);
    }


    int get_height_px(char* t)
    {

        int w,h;

        TTF_SizeText(fontset, t, &w, &h);

        return h;
    };

    SDL_Rect get_render_rect(const char* textin)
    {
        SDL_Rect rect = {0,0,0,0};

        rect.w = get_length_px((char*)textin);
        rect.h = get_height_px((char*)textin);

        return rect;
    }

    SDL_Rect text(SDL_Surface* s, const char* textin,int x, int y,int limit_width,int align = 0)
    {
        SDL_Rect rect = {0,0,0,0};
        SDL_Color tmpfontcolor = {color_r,color_g,color_b,0};
        SDL_Surface *resulting_text = 0;

        if (strlen(textin) <=0) return rect;

        resulting_text = TTF_RenderText_Blended(fontset, textin, tmpfontcolor); //better/slower

        if (!resulting_text)
            return rect;


        if (align == 1) x = x - get_length_px((char*)textin);
        if (align == 2) x = (640 / 2) - get_length_px((char*)textin) / 2;

        SDL_Rect ds = { x, y , limit_width ,FONT_SIZE};

        if (limit_width) {

            SDL_Rect sr = { 0, 0 , limit_width ,FONT_SIZE};
            SDL_BlitSurface( resulting_text,&sr, s, &ds );

        } else SDL_BlitSurface( resulting_text,0, s, &ds );

        SDL_FreeSurface(resulting_text);

        rect.w = get_length_px((char*)textin);
        rect.h = get_height_px((char*)textin);

        return rect;

    };
};

#endif //_FONTS_H_
